<template>
  <div class="grid_gadget_tempalte"  style="width:100%;height:100%" :id="id">
    <Portal to="right-disable" style="width:100%;height:100%;"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                   style="width:100%;height: 100%;border:0">
        <el-card shadow="never"
                 class="aui-card--fill content-card"
                 style="width:100%;height: 100%;border:0">
          <div style="width:100%;height:100%;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName&& widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <div>
                <MoreMenu :slicer='slicer'
                          :fitToHeight='fitToHeight'
                          :gadgetId='id'
                          :gadgetType='gadgetInfo.com'
                          @updateQuery="query"
                          :widgetName="widgetName"
                          :businessType="gadgetInfo.businessType"
                          :id="gadgetInfo.id"
                          @showQueryModel="showQueryModel"
                          @fullScreen="fullScreen" />
              </div>
            </div>

            <div class="control-section"
                  style="margin:10px;height:100%;">
              <ejs-treegrid v-if="isHasData"
                            :dataSource='comDataList'
                            childMapping='subtasks'
                            :height='gadgetHeight - 207'
                            :treeColumnIndex='1'
                            :allowPaging='gadgetSetting.report.allowPaging'
                            :pageSettings='gadgetSetting.report.pageSettings'
                            :toolbar="gadgetSetting.report.toolbar"
                            :allowTextWrap='gadgetSetting.report.allowTextWrap'
                            :showColumnMenu='true'
                            :load="load"
                            :showColumnChooser="true"
                            :dataBound="dataBound"
                            ref="treegrid">
                <e-columns v-if="gadgetSetting.report.columns && gadgetSetting.report.columns.length > 0">
                  <e-column v-for="(columnItem, index) in gadgetSetting.report.columns"
                            :key="index"
                            :maxWidth="columnItem.maxWidth?columnItem.maxWidth:'auto'"
                            :autoFit="columnItem.autoFit"
                            :field='columnItem.field'
                            :headerText='columnItem.headerText'
                            :sortComparer='columnItem.type === "number"?sortComparer:""'
                            :textAlign="columnItem.textAlign"
                            :disableHtmlEncode="columnItem.disableHtmlEncode"
                            :headerTemplate='employeetemplate'
                            :allowFiltering="columnItem.allowFiltering"
                            :allowReordering="columnItem.allowReordering"
                            :visible='columnItem.visible'>
                  </e-column>
                </e-columns>
              </ejs-treegrid>
              <div v-else
                     class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> --> -->
                  </div>

              </div>
            </div>

          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :selectFields="selectFields"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  ref="drill-through"
                  :widgetName='widgetName' />
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import { listToTree } from '@/utils/helperTree'

export default {
  mixins: [mixinGadgetViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model') },
  data () {
    return {
        employeetemplate: function () {
        return {
          template: Vue.component('employeetemplate', {
            template: ` <el-tooltip class="item" effect="dark" :content="$data.data.headerTextTooltip" placement="top-start" v-if="$data.data.headerTextTooltip">
                          <div style="text-align:left">{{$data.data.headerText}}</div>
                        </el-tooltip>
                         <div v-else style="text-align:left">{{$data.data.headerText}}</div>
                        `
          })
        }
      },
      currentTime: null,
      gadgetSetting: {},
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      dataList: [],
      loading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'treegridgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'treegridgadget' }).gadgetSetting
        }
      },
      conditionFormat: [],
      queryId: '',
      selectFields: [],
      widgetName: '',
      linkedDatasetList: []

    }
  },

  created () {
    // this.query()
    Vue['_this'] = this

    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  computed: {
    comDataList () {
      var _self = this
      var currentData = []
      currentData = _self.dataList
      var subKey = this.gadgetSetting.report.subtasks
      var pidKey = this.gadgetSetting.report.groupFields
      let config = {
        id: `${subKey}`,
        children: 'subtasks',
        pid: `${pidKey}`
      }
      var retdata = listToTree(currentData, config)
      return retdata
    }
  },
  watch: {
    editMode (val) {
      if (!val) {
        this.saveGadgetSetting()
      }
    }
  },
  methods: {
    sortComparer: function (reference, comparer) {
      if (reference === 0 && this.isNull(comparer)) {
        return 1
      }
      if (Number(reference) < Number(comparer)) {
        return -1
      }
      if (Number(reference) > Number(comparer)) {
        return 1
      }
      return 0
    },
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        this.applyGadgetSetting()
      }
    },
    load (args) {
      this.treegrid = this.$refs.treegrid
      this.gadgetHeight = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100  : this.gadgetInfo.h * 20 - 15
    },
    applyGadgetSetting () {
      this.gadgetSetting.report = this._.merge(this.gadgetSetting.report, JSON.parse(this.treegrid.ej2Instances.getPersistData()))
      this.$refs.treegrid.ej2Instances.setProperties(this.gadgetSetting.report)
      this.$forceUpdate()
    },
    saveGadgetSetting () {
      var _self = this
      if (_self.grid) {
        // need edwin look
        var report = JSON.parse(_self.treegrid.ej2Instances.getPersistData())
        // var nowGridSetting =
        _self._.merge(_self.gadgetSetting.report, report)
        // delete _self.gadgetSetting.report
        // grid table , save obj  from json obj
        // const params = {
        //   gadgetSetting: {
        //     ..._self.gadgetSetting
        //     // report: nowGridSetting
        //   },
        //   gadgetId: this.id
        // }

        // this.$interface.reports.putReportsSettingApi(params).then(({ data: res }) => {
        //   if (res.code !== 0) {
        //     return _self.$message.error(res.msg)
        //   }
        // })
      }
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query(true)
    },
    queryModelPreview () {
      this.query(true)
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = newH * 20 - this.heightoffset - 15
      this.gadgetWidth = newWPx
    },

    query (e) {
      if (this.loading) {
        return false
      }
      this.dataList = []
      try {
        this.gadgetSetting.report.columns = []
      } catch (error) { }
      if (e !== 'auto') {
        this.loading = true
        this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!param.pageId) {
        param.type = 'widget'
      }
      _self.selectFields = []
      _self.$interface.reports.getReportDataInfo(param)
        .then(({ data: res }) => {
          _self.linkedDatasetList = res.datasetSync ? res.datasetSync : []
          _self.verifyHasData(res)
          _self.heightoffset = 5
          _self.gadgetHeight = _self.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100  :(_self.gadgetInfo.h * 20) - _self.heightoffset - 15
          if (res.config) {
            _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
          }
          if (res.name) {
            _self.widgetName = res.name
          } else if (this.wName) {
            _self.widgetName = this.wName
          } else {
            _self.widgetName = _self.gadgetSetting.headerTitle
          }
          _self.selectFields = res.selectFields

          _self.isGridInit = false
          // process data
          if (res.data) {
            //res.data = JSON.parse(JSON.stringify(res.data))
            _self.dataList = _self.formatData(JSON.parse(JSON.stringify(res.data)), res.selectFields, 'gridgadget')
          }
          _self.isGridInit = false
        })
        .catch((error) => {
          if (this.wName) {
          this.widgetName = this.wName
          }
          this.isHasData = false
          _self.loading = false
          if (error.response && error.response.status === 504) {
            this.errorStatus = '504'
            this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
          }
        }).finally(() => {
          this.currentTime = new Date()
          this.autoRefreshQuery(e)
          this.updateGadgetLoadingStatus(!this.loading)
        })
    },
    destroyed () {
      delete Vue['_this']
    },
    remove () {
      this.close()
      if (this.drop.parentNode) {
        this.drop.parentNode.removeChild(this.drop)
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.content-card {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 45%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
::v-deep .e-dlg-content {
  max-height: 140px;
   overflow-y: auto;
}
::v-deep .e-rowcell {
  white-space: pre-wrap!important;
}
.grid_gadget_tempalte ::v-deep .showToobar .e-grid .e-toolbar {
  display: none;
}
.grid_gadget_tempalte ::v-deep .e-grid .e-summarycell {
  font-size: 13px;
  background-color: #f6f6f6;
  border-color: #e0e0e0;
  color: rgba(0, 0, 0, 0.54);
  font-weight: normal;
}
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.e-grid ::v-deep .e-filter-popup {
  max-height: 300px !important;
  overflow-y: auto;
}

::v-deep .e-grid .e-ccdlg .e-cc-contentdiv {
  height: 110px;
  overflow-y: auto;
}
.e-grid ::v-deep .e-checkboxlist {
  height: auto !important;
  overflow-y: visible !important;
}
</style>
